package com.sk.weichat.ui.base;

import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public abstract class EditBaseActivity extends BaseActivity {

    @Override
    public boolean dispatchTouchEvent(MotionEvent pEv) {
        if (pEv.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isShouldHideInput(view, pEv)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(pEv);
        }

        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(pEv)) {
            return true;
        }

        return onTouchEvent(pEv);
    }

    /**
     * EditText失去焦点后（点击其他地方），收起键盘
     * @param pView
     * @param pEv
     * @return
     */
    private boolean isShouldHideInput(View pView, MotionEvent pEv) {
        boolean isHidden = false;
        if (pView != null && pView instanceof EditText) {
            Log.v(TAG, "pViewID = " + pView.getId());
            int[] leftTop = {0, 0};
            // 获取输入框在当前屏幕上的位置
            pView.getLocationOnScreen(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + pView.getHeight();
            int right = left + pView.getWidth();
            // 获取光标(触摸点)在当前屏幕上的位置
            float locationX = pEv.getRawX();
            float locationY = pEv.getRawY();
            if (locationX > left && locationX < right
                    && locationY > top && locationY < bottom) {
                // 点击的是输入框区域，保留点击EditText事件
                isHidden = false;
            } else {
                // 失去焦点
                pView.clearFocus();
                isHidden = true;
            }
        }
        return isHidden;
    }
}
